import os
import platform
import subprocess
import sys

from task_manager import manager
from task_manager.ListHandler import ListHandler
from task_manager.RunTask import RunTask

# 脚本基础路径
basePath = os.path.dirname(os.path.abspath(__file__))
# 日志基础路径
logBasePath = os.path.dirname(os.path.abspath(__file__)) + "/runtime/manager/"
# 当前文件名
script = basePath + "/" + str(__file__)

def get_pid():
    (status, output) = subprocess.getstatusoutput(
        "ps -ef |grep -v grep|grep -v 'sh -c' | grep '" + script + "' | awk '{print $2}'")

    if output:
        return output

    return None


# 开启主进程
if manager.action == "start":
    # 判断操作系统类型
    method = ListHandler.get(sys.argv, 2)
    sysStr = platform.system()
    if (sysStr == "Windows"):
        if method == "d":
            print("Windows系统不支持后台运行")
            exit()
        RunTask(logBasePath=logBasePath).execute()
    elif (sysStr == "Linux"):
        if method == "d":
            (status, output) = subprocess.getstatusoutput('nohup python3 {} start > /dev/null 2>&1 &'.format(script))
            if status == 0:
                pid = get_pid()
                print("manager has running at {} !!!".format(pid))
            else:
                print("ERROR:" + output)
        else:
            RunTask(logBasePath=logBasePath).execute()
    else:
        print("{}:该操作系统为测试".format(sysStr))

# 查看状态
if manager.action == "status":
    pid = get_pid()
    if pid:
        print("##########INFO######################################################\n")
        print(script + ":is running!!!")
        print("PID:" + pid + "\n")
        print("####################################################################")
    else:
        print(script + ":is not running!!!")

# 停止
if manager.action == "stop":
    pid = get_pid()
    if not pid:
        print(script + ":is not running!!!")
    (status, output) = subprocess.getstatusoutput("kill -9 {}".format(pid))
    if status == 0:
        print("PID {} has been killed".format(pid))
    else:
        print("ERROR:" + output)


if manager.action == "restart":
    pid = get_pid()
    if not pid:
        print("manager is not running!!!")
        print("start manager...")
    else:
        (status, output) = subprocess.getstatusoutput("kill -9 {}".format(pid))
        if status == 0:
            print("PID {} has been killed")
        else:
            print("ERROR:" + output)
            exit()

    (status, output) = subprocess.getstatusoutput('nohup python3 {} start > /dev/null 2>&1 &'.format(script))
    if status == 0:
        pid = get_pid()
        print("manager has running at {} !!!".format(pid))
    else:
        print("ERROR:" + output)




